package com.daijt.mobile.service.hibernate;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.stereotype.Service;

import com.daijt.mobile.persistence.CheckList;
import com.daijt.mobile.service.CheckListService;

@Service
public class CheckListServiceImpl extends JpaDaoSupport implements
		CheckListService {

	@Autowired
	@Required
	public void setJpaEntityManagerFactory(
	        @Qualifier("entityManagerFactory")EntityManagerFactory entityManagerFactory) {
		super.setEntityManagerFactory(entityManagerFactory);
	}
	
	public List<CheckList> getCheckListsByUser(final long userId) {
		@SuppressWarnings("unchecked")
		List<CheckList> lists = (List<CheckList>)getJpaTemplate().execute(new JpaCallback<List<CheckList>>() {

			public List<CheckList> doInJpa(EntityManager em)
					throws PersistenceException {
				Session session = (Session) em.getDelegate();
				
				Criteria criteria = session.createCriteria(CheckList.class).setFetchMode("items", FetchMode.JOIN)
					.add(Restrictions.eq("owner.userId", userId)).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
				
				List<CheckList> usrsLists = (List<CheckList>) criteria.list();
				
				return usrsLists;
			}
			
		});
		
		return lists;
	}


	public void removeCheckList(CheckList list) {
		
		getJpaTemplate().remove(list);
	}

	public CheckList getCheckListById(long id) {
		
		return getJpaTemplate().find(CheckList.class, id);
	}

	public void persistCheckList(CheckList list) {
		getJpaTemplate().persist(list);
		getJpaTemplate().flush();
	}

	public CheckList mergeCheckList(CheckList list) {
		CheckList updatedList = getJpaTemplate().merge(list);
		return updatedList;
	}

	public CheckList getFullCheckListById(final long id) {
		
		CheckList alist =  getJpaTemplate().execute(new JpaCallback<CheckList>(){

			public CheckList doInJpa(EntityManager em)
					throws PersistenceException {
				
				Session session = (Session) em.getDelegate();
				
				Criteria criteria = session.createCriteria(CheckList.class).setFetchMode("items", FetchMode.JOIN)
					.add(Restrictions.eq("id", id)).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
				
				return (CheckList)criteria.uniqueResult();
			}
			
		});
		
		return alist;
	}

}
